<template>
    <div class="maindiv">
        <goback :getName='goName'></goback>
        <div class="personal-information">
            <router-link :to="'/deliveryAddress/1'">
                <div class="personal-info">
                    <div class="blank-info" v-if="isBlank">请填写收货信息</div>
                    <div class="personal-name">
                        <span>{{userInfomation.name}}</span>
                    </div>
                    <div class="personal-tel">{{telEncrypt}}</div>
                    <div class="personal-address">
                        <span>{{userInfomation.address}}</span>
                    </div>
                    <span class="revise">
                        <img src="../../assets/other/goback.png" alt="">
                    </span>
                </div>
            </router-link>
            <div class="border">
            </div>
            <!-- <div class="pay">
                <div class="bean">
                    <span>支付方式 ：</span>
                    <div>
                        <span class="pay-name">乐豆</span>
                        <span class="minusOrPlus" @click="minus('beanCount')">-</span>
                        <input type="number" class="pay-count" name="beanCount" v-model="beanCount">
                        <span class="minusOrPlus" @click="plus('beanCount')">+</span>
                    </div>
                </div>
                <div class="wx">
                    <span>剩余乐豆：{{allBeanCount}}</span>
                    <div>
                        <span class="pay-name">现金</span>
                        <span class="minusOrPlus" @click="minus('wxCount')">-</span>
                        <input type="number" class="pay-count" name="wxCount" v-model="wxCount" disabled="disabled">
                        <span class="minusOrPlus" @click="plus('wxCount')">+</span>
                    </div>
                </div>
            </div> -->
        </div>
        <dl class="goods-list">
            <dd v-for="(goods,index) of goodses" :key="index">
                <div class="goods-img">
                    <img :src="goods.product.thumbnail" alt="">
                </div>
                <div class="goods-info">
                    <span class="goods-name">{{goods.product.productName}}</span>
                    <span class="goods-price" v-if="!isReceive">￥{{goods.product.defaultPrice}}</span>
                    <span class="goods-price" v-if="isReceive">￥0</span>
                    <span class="goods-count">x{{goods.product.num}}</span>
                </div>
                <div class="postage" v-if="isReceive">
                    <div>邮费：</div>
                    <div>{{goods.product.defaultPrice}}</div>
                </div>
            </dd>
            
        </dl>
        <dl class="order">
            <dd class="order-price">
                <span class="symbol">￥</span>
                <span>{{totalPrice}}</span>
                <span class="postageWords" v-if="isReceive">（邮费）</span>
            </dd>
            <dd class="submit-order" @click="submitOrder">{{submitWord}}</dd>
        </dl>
    </div>
</template>
<script>
    import goback from '../../components/goback'
    import pingpp from 'pingpp-js'
    import { userInfoGet, payview } from '../../libs/publicMethod'  // 获取用户信息
    import { getAddressList, getProductInfosBySkuId, getAccountAmount, buyMask, claimMask, isChannel } from '../../libs/interface' // 获取接口
    import { Indicator } from 'mint-ui'
    import area from '../../libs/area.json'
    export default {
        components: { goback, getAddressList, getProductInfosBySkuId, getAccountAmount, payview, Indicator, pingpp, buyMask, claimMask, isChannel },
        data() {
            return {
                userInfo: userInfoGet(), // 用户信息
                goName: '确认订单',
                allBeanCount: 0, //剩余乐豆
                beanCount: 0, //乐豆
                wxCount: 0, //微信
                isBlank: true, //默认地址是否为空
                channel: 'wx_pub', // 充值方式 ：微信———>wx_pub
                //用户信息
                userInfomation: {
                    tel: '',
                    name: '',
                    address: '',
                },
                goodses: [],
                totalPrice: 0,
                num: 1,
                submitWord: '提交订单',
                isReceive: false,
            }
        },
        methods: {
            minus(count) {
                let vm = this
                if (count === 'beanCount') {
                    vm.beanCount--
                }
                if (count === 'wxCount') {
                    vm.wxCount--
                }
            },
            plus(count) {
                let vm = this
                if (count === 'beanCount') {
                    vm.beanCount++
                }
                if (count === 'wxCount') {
                    vm.wxCount++
                }
            },
            submitOrder() {
                let vm = this
                if (vm.isBlank) {
                    vm.$toast('请填写收货信息')
                    return
                }
                // 领取商品
                if (sessionStorage.getItem('receiveGoods')) {
                    let params = {
                        skuId: vm.$route.params.id,
                        memberId: vm.userInfo.id,
                        info: JSON.stringify(vm.userInfomation).replace('tel', '联系电话').replace('name', '姓名').replace('address', '收货地址'),
                    }
                    Indicator.open({
                        text: '支付中...',
                        spinnerType: 'fading-circle'
                    })
                    if (vm.wxCount > 0) {
                        payview(vm.wxCount, vm.channel, (data) => {
                            Indicator.close()
                            // vm.wxCount = 0
                            try {
                                pingpp.createPayment(data, function (result, err) {
                                    if (result == "success") {
                                        Indicator.open({
                                            text: '支付中...',
                                            spinnerType: 'fading-circle'
                                        })
                                        var xx = setTimeout(() => {
                                            vm.wxCount = 0
                                            claimMask(params, (buyData) => {
                                                Indicator.close()
                                                if (buyData.code === 1) {
                                                    sessionStorage.removeItem('addressinfoSet')
                                                    vm.$toast('领取成功！')
                                                    sessionStorage.setItem('getPoints', JSON.stringify({ points: vm.tPrice }))
                                                    vm.$router.replace('/facialMask')
                                                } else {
                                                    vm.$toast(buyData.msg)
                                                    location.replace('https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx163c4c3d188f8ee5&redirect_uri=http%3A%2F%2Fwww.xiewan8.com%2FlyApp%2F%23%2FfaciaMaskPay%2F' + vm.$route.params.id + '&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect')
                                                }
                                            })
                                        }, 2500)
                                        // 只有微信公众账号 wx_pub 支付成功的结果会在这里返回，其他的 wap 支付结果都是在 extra 中对应的 URL 跳转。
                                    } else if (result == "fail") {
                                        alert("错误信息：charge 不正确或者微信公众账号支付失败时")
                                        // charge 不正确或者微信公众账号支付失败时会在此处返回
                                    } else if (result == "cancel") {
                                        // 微信公众账号支付取消支付
                                    }
                                })
                            } catch (error) {
                                location.replace('https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx163c4c3d188f8ee5&redirect_uri=http%3A%2F%2Fwww.xiewan8.com%2FlyApp%2F%23%2FfaciaMaskPay%2F' + vm.$route.params.id + '&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect')
                            }
                        })
                    } else {
                        claimMask(params, (data) => {
                            Indicator.close()
                            if (data.code === 1) {
                                vm.$toast('领取成功！')
                                sessionStorage.setItem('getPoints', JSON.stringify({ points: vm.tPrice }))
                                vm.$router.replace('/facialMask')
                            } else {
                                vm.$toast(data.msg)
                            }
                        })
                    }
                } else {
                // 购买商品
                    let params = {
                        skuId: vm.$route.params.id,
                        memberId: vm.userInfo.id,
                        info: JSON.stringify(vm.userInfomation).replace('tel', '联系电话').replace('name', '姓名').replace('address', '收货地址'),
                        inviterId: sessionStorage.getItem('inviterID') ? sessionStorage.getItem('inviterID') : -1,
                    }
                    if (params.memberId == params.inviterId) {
                        params.inviterId = -1
                    }
                    Indicator.open({
                        text: '支付中...',
                        spinnerType: 'fading-circle'
                    })
                    if (vm.wxCount > 0) {
                        payview(vm.wxCount, vm.channel, (data) => {
                            Indicator.close()
                            // vm.wxCount = 0
                            try {
                                pingpp.createPayment(data, function (result, err) {
                                    if (result == "success") {
                                        Indicator.open({
                                            text: '支付中...',
                                            spinnerType: 'fading-circle'
                                        })
                                        var xx = setTimeout(() => {
                                            vm.wxCount = 0
                                            buyMask(params, (buyData) => {
                                                Indicator.close()
                                                if (buyData.code === 1) {
                                                    sessionStorage.removeItem('addressinfoSet')
                                                    vm.$toast('购买成功！')
                                                    let param = {
                                                        memberId: vm.userInfo.id
                                                    }
                                                    isChannel(param, (data) => {
                                                        if (data.code === 1) {
                                                            if (!data.payload) {
                                                                sessionStorage.setItem('applyChannel', JSON.stringify({ channel: true }))
                                                            } else {
                                                                sessionStorage.setItem('applyChannel', JSON.stringify({ channel: false }))
                                                            }
                                                            location.replace('http://www.xiewan8.com/lyApp/#/facialMask')
                                                        }
                                                    })
                                                } else {
                                                    vm.$toast(buyData.msg)
                                                    location.replace('https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx163c4c3d188f8ee5&redirect_uri=http%3A%2F%2Fwww.xiewan8.com%2FlyApp%2F%23%2FfaciaMaskPay%2F' + vm.$route.params.id + '&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect')
                                                }
                                            })
                                        }, 2500)
                                        // 只有微信公众账号 wx_pub 支付成功的结果会在这里返回，其他的 wap 支付结果都是在 extra 中对应的 URL 跳转。
                                    } else if (result == "fail") {
                                        alert("错误信息：charge 不正确或者微信公众账号支付失败时")
                                        // charge 不正确或者微信公众账号支付失败时会在此处返回
                                    } else if (result == "cancel") {
                                        // 微信公众账号支付取消支付
                                    }
                                })
                            } catch (error) {
                                location.replace('https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx163c4c3d188f8ee5&redirect_uri=http%3A%2F%2Fwww.xiewan8.com%2FlyApp%2F%23%2FfaciaMaskPay%2F' + vm.$route.params.id + '&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect')
                            }
                        })
                    } else {
                        buyMask(params, (data) => {
                            Indicator.close()
                            if (data.code === 1) {
                                vm.$toast('购买成功！')
                                let param = {
                                    memberId: vm.userInfo.id
                                }
                                isChannel(param, (data) => {
                                    if (data.code === 1) {
                                        if (!data.payload) {
                                            sessionStorage.setItem('applyChannel', JSON.stringify({ channel: true }))
                                        } else {
                                            sessionStorage.setItem('applyChannel', JSON.stringify({ channel: false }))
                                        }
                                        location.replace('http://www.xiewan8.com/lyApp/#/facialMask')
                                    }
                                })
                                vm.$router.replace('/facialMask')
                            } else {
                                vm.$toast(data.msg)
                            }
                        })
                    }
                }
            }
        },
        mounted() {
            let vm = this
            let params = {
                memberid: vm.userInfo.id,
            }
            if (!sessionStorage.getItem('addressinfoSet')) {
                getAddressList(params, (data) => {
                    if (data.code === 1) {
                        if (data.payload < 1) {
                            this.isBlank = true
                        } else {
                            this.isBlank = false
                            data.payload.forEach(elem => {
                                if (elem.isdefault === 1) {
                                    vm.userInfomation.name = elem.name
                                    vm.userInfomation.tel = elem.phone
                                    vm.userInfomation.address = elem.address
                                }
                            })
                        }
                    } else {
                        vm.$toast('获取地址失败')
                    }
                })
            } else {
                vm.isBlank = false
                let addressInfo = JSON.parse(sessionStorage.getItem('addressinfoSet'))
                vm.userInfomation.name = addressInfo.name
                vm.userInfomation.tel = addressInfo.phone
                vm.userInfomation.address = addressInfo.address
            }
            let param = {
                skuId: vm.$route.params.id,
                memberId: vm.userInfo.id,
            }
            getProductInfosBySkuId(param, (data) => {
                if (data.code === 1) {
                    vm.goodses.push(data.payload)
                    vm.goodses[0].product.productName = data.payload.product.name
                    vm.goodses[0].product.defaultPrice = (vm.goodses[0].product.defaultPrice / 100).toFixed(2)
                    if (sessionStorage.getItem('receiveGoods')) {
                        vm.isReceive = true
                        if (vm.isBlank) {
                            vm.goodses[0].product.defaultPrice = (18).toFixed(2)
                        } else {
                            area.forEach(ele => {
                                if (vm.userInfomation.address.substring(0, 3) === ele.province) {
                                    vm.goodses[0].product.defaultPrice = (ele.price / 100).toFixed(2)
                                }
                            })
                        }
                    }
                    vm.goodses[0].product.num = 1
                    vm.tPrice = 0
                    vm.goodses.forEach((elem) => {
                        vm.tPrice += elem.product.num * elem.product.defaultPrice
                    })
                    vm.totalPrice = vm.tPrice.toFixed(2)
                    let paramss = {
                        memberid: vm.userInfo.id,
                    }
                    getAccountAmount(params, (data) => {
                        if (data.code === 1) {
                            vm.allBeanCount = data.payload.lb
                            if (vm.allBeanCount - vm.totalPrice >=0) {
                                // vm.beanCount = vm.totalPrice
                                // vm.wxCount = 0
                                vm.beanCount = 0
                                vm.wxCount = Math.ceil(vm.totalPrice)
                            } else {
                                // vm.beanCount = vm.allBeanCount
                                // vm.wxCount = Math.ceil(vm.totalPrice - vm.beanCount)
                                vm.beanCount = 0
                                vm.wxCount = Math.ceil(vm.totalPrice)
                            }
                            console.log(vm.wxCount)
                            // vm.beanCount = 0
                            // vm.wxCount = Math.ceil(vm.totalPrice)
                        } else {
                            vm.$toast(data.msg)
                        }
                    })
                } else {
                    vm.$toast('系统异常')
                }
            })
        },
        computed: {
            //手机号中间4位隐藏
            telEncrypt() {
                return this.userInfomation.tel.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
            },
        },
        watch: {
            // beanCount() {
            //     let vm = this
            //     if (vm.beanCount - 0 < 0) {
            //         vm.beanCount = 0
            //     }
            //     if (vm.beanCount - vm.totalPrice > 0) {
            //         vm.beanCount = vm.totalPrice
            //     }
            //     if (vm.beanCount - vm.allBeanCount > 0) {
            //         vm.beanCount = vm.allBeanCount
            //     }
            //     vm.beanCount = (vm.beanCount - 0).toFixed(2)
            //     vm.wxCount = Math.ceil(vm.totalPrice - vm.beanCount)
            // },
            // wxCount() {
            //     let vm = this
            //     if (vm.wxCount - 0 < 0) {
            //         vm.wxCount = 0
            //     }
            //     if (vm.wxCount - Math.ceil(vm.totalPrice) > 0) {
            //         vm.wxCount = Math.ceil(vm.totalPrice)
            //     }
            //     vm.wxCount = Math.ceil(vm.wxCount)
            //     vm.beanCount = (vm.totalPrice - Math.ceil(vm.wxCount)).toFixed(2)
            // },
        }
    }
</script>
<style scoped>
a {
    color: #333;
}

.maindiv {
    height: 100%;
    width: 100%;
    position: absolute;
    overflow: hidden;
}

.head-title {
    position: absolute;
    top: 0;
    left: 2.5rem;
    font-size: .8rem;
}

.personal-information {
    background-color: #fff;
    /* height: 12rem; */
    height: 6rem;
    width: 94%;
    border-radius: .6rem;
    margin: .4rem auto;
    overflow: hidden;
}

.personal-info {
    /* height: 50%; */
    height: 100%;
    position: relative;
    text-align: left;
}

.blank-info {
    position: absolute;
    width: 100%;
    font-size: 1.6rem;
    height: 2.1rem;
    color: #F23030;
    top: 0;
    bottom: 0;
    margin: auto 1rem;
}

.personal-name {
    display: inline-flex;
    align-items: flex-end;
    height: 50%;
    width: 28%;
    margin-left: 1rem;
    font-size: 1.2rem;
}

.personal-name span {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.personal-tel {
    display: inline-flex;
    align-items: flex-end;
    height: 50%;
    font-size: 1.2rem;
}

.personal-address {
    width: 82%;
    height: 50%;
    font-size: .7rem;
    margin-left: 1rem;
    position: relative;
}

.personal-address span {
    position: absolute;
    margin: auto;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    height: 50%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.revise {
    display: inline-block;
    transform: rotateY(180deg);
    width: 1.2rem;
    height: 1.2rem;
    position: absolute;
    margin: auto;
    right: 1rem;
    top: 0;
    bottom: 0;
}

.revise img {
    width: 100%;
    height: 100%;
}

.border {
    width: 96%;
    height: .22rem;
    margin: 0 auto;
    background-image: url('../../assets/other/red.png');
    background-size: contain;
    background-repeat: repeat-x;
    background-position: center;
}

.pay {
    height: 50%;
}

.bean {
    height: 50%;
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    font-size: .95rem;
    margin: -.2rem 2.3rem .3rem 1.5rem;
    color: #333;
}

.bean span,
.wx span {
    display: inline-block;
}

.bean>span,
.wx>span {
    text-align: left;
    width: 40%;
    white-space: nowrap;
    font-size: .9rem;
}

.bean>div,
.wx>div {
    margin-right: -7%;
}

.bean>div span,
.wx>div span {
    margin-left: .7rem;
}

.pay-name {
    font-size: .9rem;
}

.pay .pay-count {
    width: 3rem;
    height: 1.5rem;
    background-color: #F6F6F6;
    outline: none;
    border: none;
    text-align: center;
    margin-left: .7rem;
    font-size: .95rem;
}

.wx {
    height: 33%;
    margin: 0 2.3rem 0 1.5rem;
    font-size: .95rem;
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
}

.minusOrPlus {
    font-size: 1.45rem;
}
.postage{
    position: absolute;
    display: flex;
    align-items: center;
    top: 30%;
    width: 47%;
    /* border: 1px solid red; */
    right: 0;
    font-size: 1rem;
}
.postage>div:last-child{
    margin-top: 2%;
}
.goods-list {
    background-color: #fff;
    width: 94%;
    height: 40%;
    margin: .4rem auto;
    overflow: auto;
    border-radius: .6rem;
    padding-bottom: 11rem;
    position: relative;
}

.goods-list>dd {
    display: flex;
    justify-content: space-around;
    margin-top: 1rem;
}

.goods-list .goods-img {
    width: 8rem;
    height: 6rem;
}

.goods-list .goods-img img {
    display: block;
    width: 100%;
    height: 100%;
}

.goods-info {
    width: 45%;
    font-size: .7rem;
    position: relative;
}

.goods-info span {
    display: block;
    text-align: left;
    transform: scale(.9);
}

.goods-name {
    color: #333;
    margin: 8% 0 8% 0;
}

.goods-price {
    font-size: 1rem;
    font-weight: bold;
    color: #F23030;
}

.goods-count {
    position: absolute;
    bottom: .8rem;
    right: 0;
    font-size: 1rem;
}

.order {
    position: fixed;
    bottom: 0;
    display: flex;
    width: 100%;
}

.order-price {
    width: 65%;
    height: 3.3rem;
    line-height: 3.3rem;
    background: linear-gradient(0deg, #F5F5F5, #FFFFFF);
    -moz-box-shadow: 0rem -2rem 5rem 0rem rgba(179, 177, 171, 0.2);
    -webkit-box-shadow: 0rem -2rem 5rem 0rem rgba(179, 177, 171, 0.2);
    box-shadow: 0rem -2rem 5rem 0rem rgba(179, 177, 171, 0.2);
    color: #F23030;
    font-size: 1.3rem;
    font-weight: bold;
    text-align: left;
    padding: 0 1rem;
}
.postageWords{
    font-size: .9rem;
}
.symbol {
    font-size: .9rem;
}

.submit-order {
    width: 35%;
    height: 3.3rem;
    line-height: 3.3rem;
    background: linear-gradient(0deg, rgba(226, 35, 25, 1), rgba(253, 55, 8, 1));
    -moz-box-shadow: 0rem -2rem 5rem 0rem rgba(179, 177, 171, 0.2);
    -webkit-box-shadow: 0rem -2rem 5rem 0rem rgba(179, 177, 171, 0.2);
    box-shadow: 0rem -2rem 5rem 0rem rgba(179, 177, 171, 0.2);
    font-size: 1.1rem;
    color: #fff;
}
</style>